<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>飞花令</title>
    <link rel="stylesheet" href="/css/common.css" type="text/css">
    <script src="/js/jquery/jquery-3.4.1.js"></script>
    <script src="/js/service/common.js"></script>
    <script>
        let flyingId, progressId;
        function start() {
            flyingId = -1;
            changeTipPage("flyingFlower");
            $("#log").html(`<div id="system" style="padding-left: 6%; padding-top: 1%">
                </div>
                <div id="user" style="padding-left: 54%; padding-top: 1%">
                </div>`);
            let keyWord = $('#keyWord');
            keyWord.val('');
            keyWord.removeAttr("readonly");
            $("#start").removeAttr("disabled");
        }
        let kValue;
        function startFlyingFlower() {
            progressId = null;
            let keyWord = $('#keyWord');
            let keyWordValue = keyWord.val();
            if(!keyWordValue){
                alert("关键字不能为空！！！");
                return;
            }
            kValue = keyWordValue;
            keyWord.val(`本轮关键字：${keyWordValue}`);
            keyWord.attr("readonly", "readonly");
            $("#start").attr("disabled", "disabled");
            getSysContent(keyWordValue);
        }
        function getSysContent(value){
            flyingId = flyingId ? flyingId : -1;
            $.ajax({
                url: `/flyingFlower/getContentByKeyWord?keyWord=${value}&flyingId=${flyingId}`,
                dataType: 'json',
                type: "GET",
                success: function (json) {
                    if(json.code === 200) {
                        flyingId = json.data.flyingId;
                        let html = `<span style="color: burlywood">
                                        系统：
                                    </span><br>
                                    <span>
                                        ${replaceKeyWord(json.data.answer, kValue)}
                                    </span>`;
                        $("#system").html(html);
                    }else if(json.code === 2001){
                        alert(json.message);
                        window.location.reload();
                    }else{
                        tipsMessage(json);
                    }
                }
            });
        }
        let nextDiv = `<div id="system1" style="padding-left: 6%; padding-top: 1%">
                        </div>
                        <div id="user1" style="padding-left: 54%; padding-top: 1%">
                        </div>`;
        function submitResults(target) {
            let keyWord = kValue;
            let answer = $(target).prev('input').val();
            if(!(answer || answer.trim() === '')){
                alert("请输入诗句！！！");
                return;
            }
            $.ajax({
                url: "/flyingFlower/saveFlyingFlowerAnswer",
                type: "POST",
                data: JSON.stringify({
                    flyingId: flyingId,
                    keyWord: keyWord,
                    answer: answer
                }),
                contentType: 'application/json',
                success: function (json) {
                    if(json.code === 200){
                        $(target).prev('input').val('');
                        let html = `<span style="color: burlywood">
                                        ${getUser().username}：
                                    </span><br>
                                    <span>
                                        ${replaceKeyWord(answer, kValue)}
                                    </span>`;
                        let user = $("#user");
                        user.html(html);
                        user.parent().append(nextDiv);
                        user.removeAttr("id");
                        $("#system").removeAttr("id");
                        $("#user1").attr("id", "user");
                        $("#system1").attr("id", "system");
                        getSysContent(keyWord);
                    }else{
                        tipsMessage(json);
                    }
                }
            });
        }
        function finish() {
            if(confirm("结束本轮游戏？")){
                $.ajax({
                    url: `/flyingFlower/finish/${flyingId}`,
                    type: "PUT",
                    dataType: 'json',
                    success: function (json) {
                        if(json.code === 200){
                            flyingId = null;
                            progressId = null;
                            window.location.reload();
                        }
                    }
                });
            }
        }
        function saveProgress() {
            let flyingFlowerHtml = $("#log").html();
            $.ajax({
                url: `/progress/saveProgress`,
                type: "POST",
                dataType: 'json',
                data: JSON.stringify({
                    id: progressId,
                    type: 5001,
                    relationId: flyingId,
                    htmlStr: flyingFlowerHtml
                }),
                contentType: 'application/json',
                success: function (json) {
                    if(json.code === 200){
                        flyingId = null;
                        alert('成功！！');
                        $("#btnGroup").css("display", "block");
                        window.location.reload();
                    }else {
                        tipsMessage(json);
                    }
                }
            });
        }
        function flyingFlowerHistory() {
            changeTipPage("flyingFlowerHistory");
            let keyWord = $('#historyKeyWord').val();
            let param = `?status=${$("#status option:selected").val()}`;
            if(keyWord && keyWord.trim() !== ''){
                param += `&keyWord=${keyWord}`;
            }
            $.ajax({
                url: `/flyingFlower/flyingFlowerHistory${param}`,
                dataType: 'json',
                type: "GET",
                success: function (json) {
                    if(json.code === 200){
                        let html = `<tr class="table-tr-head"><td style="width: 5%">序号</td>
                                <td style="width: 15%">关键字</td>
                                <td style="width: 5%">回合</td>
                                <td style="width: 5%">得分</td>
                                <td style="width: 10%">结果</td>
                                <td style="width: 20%">开始时间</td>
                                <td style="width: 20%">结束时间</td>
                                <td style="width: 20%">操作</td></tr>`;
                        let arr = json.data;
                        if(arr){
                            for(let i = 0, j = arr.length; i < j; i++){
                                let trData = arr[i];
                                let time = trData.time;
                                let endTime = trData.endTime, continueHtml = '';
                                if(!endTime){
                                    if(time || time === 0){
                                        continueHtml = `<span class="href-next" onclick="continueProgress(${trData.id})">继续游戏</span>`;
                                        endTime = '未结束';
                                    }else{
                                        endTime = '未存档';
                                    }
                                }
                                let classId = "table-tr-content-" + ((i % 2) + 1);
                                html += `<tr class=${classId}><td>${(i + 1)}</td>
                                    <td>${trData.keyWord}</td>
                                    <td>${time}</td>
                                    <td>${trData.score}</td>
                                    <td>${trData.victory === 4001 ? '胜利' : '失败'}</td>
                                    <td>${trData.startTime}</td>
                                    <td>${endTime}</td>
                                    <td><span class="href-next" onclick="flyingFlowerDetail(${trData.id})">查看记录</span>
                                    ${continueHtml}</td>
                                    </tr>`;
                            }
                        }
                        $("#table").html(html);
                    }else{
                        tipsMessage(json);
                    }
                }
            });
        }
        function flyingFlowerDetail(flyingId) {
            changeTipPage("flyingFlowerDetail");
            $.ajax({
                url: `/flyingFlower/flyingFlowerDetail/${flyingId}`,
                dataType: 'json',
                type: 'GET',
                success: function (json) {
                    if(json.code === 200){
                        let arr = json.data;
                        let html = '';
                        if(arr){
                            for(let i = 0, j = arr.length; i < j; i ++){
                                let obj = arr[i];
                                let answer = replaceKeyWord(obj.answer, obj.keyWord);
                                if(i % 2 === 0){
                                    html += `<div style="padding-left: 6%; padding-top: 1%">
                                                <span style="color: burlywood">
                                                    ${obj.username}：
                                                </span><br>
                                                <span>
                                                    ${answer}
                                                </span></div>`;
                                }else{
                                    html += `<div style="padding-left: 54%; padding-top: 1%">
                                                <span style="color: burlywood">
                                                    ${obj.username}：
                                                </span><br>
                                                <span>
                                                    ${answer}
                                                </span></div>`;
                                }
                            }
                        }
                        $("#flyingFlowerDetailDiv").html(html);
                    }
                }
            });
        }
        function continueProgress(flying) {
            $.ajax({
                url: `/progress/continueProgress/${flying}`,
                dataType: 'json',
                type: 'GET',
                success: function (json) {
                    if(json.code === 200){
                        flyingId = flying;
                        let res = json.data;
                        changeTipPage("flyingFlower");
                        $("#log").html(res.progress.htmlStr);
                        let keyWord = $('#keyWord');
                        kValue = res.relation.keyWord;
                        keyWord.val(`本轮关键字：${kValue}`);
                        keyWord.attr("readonly", "readonly");
                        $("#start").attr("disabled", "disabled");
                    }else{
                        tipsMessage(json);
                    }
                }
            });
        }
        function ranking() {
            changeTipPage("flyingFlowerRanking");
            let num = $("#num").val();
            $.ajax({
                url: `/flyingFlower/ranking/${num}`,
                dataType: 'json',
                type: 'GET',
                success: function (json) {
                    if(json.code === 200){
                        let arr = json.data;
                        let html = `<tr class="table-tr-head"><td>排名</td><td>玩家</td><td>回合</td><td>成绩</td>
                            <td>开始时间</td><td>记录</td></tr>`;
                        for(let i = 0, j = arr.length; i < j; i ++){
                            let classId = "table-tr-content-" + ((i % 2) + 1);
                            let row = arr[i];
                            let tr = `<tr class=${classId}><td>${row.no}</td><td>${row.username}</td><td>${row.time}</td>
                            <td>${row.score}</td><td>${row.startTime}</td>
                            <td><span class="href-next" onclick="flyingFlowerDetail(${row.flyingId})">查看记录</span></tr>`;
                            html += tr;
                        }
                        $("#introduceTable").html(html);
                    }else{
                        tipsMessage(json);
                    }
                }
            });
        }
        function introduce() {
            changeTipPage("flyingFlowerIntroduce");
        }
        function changeTipPage(tipPage) {
            $(".tipPage").each((index, tip) => {
                let o = $(tip);
                if(tip.id === tipPage){
                    o.removeAttr("hidden");
                }else{
                    o.attr("hidden", "hidden");
                }
            })
        }
        window.onload = changeTipPage;
    </script>
</head>
<body>
    <object class="object-top" data="/page/common/top"></object>
    <h3 style="text-align: center" id="title">欢迎来到飞花令</h3>
    <div style="text-align: center" id="btnGroup">
        <input type="button" value="开始游戏" class="lang-btn" onclick="start()">&nbsp;&nbsp;&nbsp;
        <input type="button" onclick="flyingFlowerHistory()" value="游戏历史" class="lang-btn">
        <input type="button" onclick="ranking()" value="诸神榜" class="lang-btn">
        <input type="button" onclick="introduce()" value="玩法介绍" class="lang-btn">
    </div>
    <div id="flyingFlower" class="tipPage">
        <div class="forum-div">
            <div style="text-align: center">
                <input id="keyWord" type="text" placeholder="请输入飞花令关键字">
                <input id="start" type="button" value="开始" class="btn" onclick="startFlyingFlower(this)">
            </div>
            <div id="log">
                <div id="system" style="padding-left: 6%; padding-top: 1%">
                </div>
                <div id="user" style="padding-left: 54%; padding-top: 1%">
                </div>
            </div>
        </div>
        <div class="forum-div">
            <div style="text-align: center">
                <input type="text" placeholder="请输入诗句">
                <input type="button" value="确定" class="btn" onclick="submitResults(this)">
            </div>
            <div style="text-align: center">
                <input type="button" value="保存进度" class="lang-btn" onclick="saveProgress()">
                <input type="button" value="结束游戏" class="lang-btn" onclick="finish()">
            </div>
        </div>
    </div>
    <div id="flyingFlowerHistory" class="tipPage">
        <div class="center-div">
            <form id="form">
                <label>
                    关键字
                </label>
                <label>
                    <input id="historyKeyWord" type="text" name="keyWord">
                </label>
                <label>
                    <select id="status" name="status">
                        <option selected value="-1">全部</option>
                        <option value="1">已完成</option>
                        <option value="2">未完成</option>
                        <option value="3">未存档</option>
                    </select>
                </label>
                <label><input type="button" class="btn" value="查询" onclick="flyingFlowerHistory(1)"></label>
                <label><input type="reset" class="btn" value="重置"></label>
            </form>
        </div>
        <div style="text-align: center; margin-top:2%">
            <table id="table" class="table-content" cellspacing="0">
            </table>
        </div>
    </div>
    <div id="flyingFlowerDetail" class="tipPage">
        <div id='flyingFlowerDetailDiv' class="forum-div">
        </div>
    </div>
    <div id="flyingFlowerRanking" class="tipPage">
        <div class="introduce">
            <h3>查看前<input id="num" value="20" class="handle-input" onkeyup="ranking()">名成绩</h3>
            <table id="introduceTable" class="table-content" cellspacing="0">
            </table>
        </div>
    </div>
    <div id="flyingFlowerIntroduce" class="tipPage">
        <div class="introduce-div">
            <span class="introduce-title">规则：</span><br>
            <span>&nbsp;&nbsp;&nbsp;&nbsp;
                确定某一关键字后，玩家与系统一人一句开始说带有此关键字的诗句。</span>
            <br><br>
            <span class="introduce-title">玩法：</span><br>
            <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                点击‘开始游戏’后，输入关键字后点击‘开始’即可开始游戏。直到哪
                一方坚持不下来为止。玩家可以点击‘保存进度’来保存进度，也可以直
                接结束游戏。在‘游戏历史’页面，可以查询游戏记录，可继续之前保存
                过的游戏进度开始游戏。</span>
        </div>
    </div>
</body>
</html>